package com.chuanyang.driverh.mainmy.fragment;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.chuanyang.driverh.R;
import com.chuanyang.driverh.base.BaseListAdapter;
import com.chuanyang.driverh.base.BaseListFragment;
import com.chuanyang.driverh.base.OnCustomListener;
import com.chuanyang.driverh.responseresult.DriverSubscriptionData;
import com.chuanyang.driverh.responseresult.DriverSubscriptionResult;
import com.chuanyang.driverh.responseresult.Result;
import com.chuanyang.driverh.utils.BitmapUtil;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.eventbus.RefleshFragEvent;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;
import com.chuanyang.driverh.utils.widget.SwipeLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;


/**
 * 西风多少恨，吹不散眉弯！—唐大帅
 * @author 唐帅
 * 我订阅的货主列表
 * created at
 */

public class SubscribeFragment  extends BaseListFragment {
    private HashMap params;
    private SubscriberAdapter adapter;

    @Override
    public BaseListAdapter createAdapter() {
        return adapter=new SubscriberAdapter(getActivity());
    }

    @Override
    protected void initListener() {

    }

    @Override
    public void initView(View view) {
        super.initView(view);
        mCurrentPage = 1;
        getData();
        adapter.setOnCustomListener(new OnCustomListener()
        {
            @Override
            public void onCustomerListener(View v, int position) {
                switch (v.getId()) {
                    case R.id.tv_sub_delete:
                        deleteDriverSubscription(position);
                        break;
                    case R.id.tv_sub_zhiding:
                        DriverSubscriptionData.DataBean sunscribe = (DriverSubscriptionData.DataBean) adapter.getItem(position);
                        adapter.stick(position,sunscribe);
                        break;

                }
            }
        });
    }

    @Override
    protected void initData() {

    }

    public void onEventMainThread(RefleshFragEvent event) {
        if (event.getIndex() == 8) {
            mCurrentPage = 1;
            getData();
        }


    }

    private void getData() {
        DialogUtil.showLoadingDialog(getActivity(),"订阅...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("driverId", SharedPrefUtil.getUserId());

        MyHttpUtil.selectDriverSubscriptionList(getActivity(),params, new MyCallback<DriverSubscriptionResult>(getActivity(),new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(getActivity(), "网络异常，请稍后再试");
                springView.onFinishFreshAndLoad();
            }

            @Override
            public void onSuccess(DriverSubscriptionResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    //登录成功返回用户信息
                    if (result.getData() != null) {
                        setDataResult(result.getData().getData());
                    }
                }else{
                    springView.onFinishFreshAndLoad();
                    PrintUtil.toast(getActivity(),result.getMsg());
                }
            }
        });

    }
    private void deleteDriverSubscription(final int position)
    {
        DialogUtil.showLoadingDialog(getActivity(),"删除订阅...");
        DriverSubscriptionData.DataBean bean1= (DriverSubscriptionData.DataBean) adapter.getItem(position);
        Map<String,String> params=new HashMap<String, String>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("shipperId", bean1.getUserId()+"");
        MyHttpUtil.deleteDsByDriverAndShipper(getActivity(),params, new MyCallback<Result>(getActivity(),new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(getActivity(), "网络异常，请稍后再试");
            }

            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                        PrintUtil.toast(getActivity(),"删除订阅成功");
                        adapter.remove(position);
                }else{
                    PrintUtil.toast(getActivity(),result.getMsg());
                }
            }
        });
    }

    @Override
    protected void onForceRefresh() {
        super.onForceRefresh();
        mCurrentPage = 1;
        getData();
    }

    @Override
    public void onGetMore() {
        getData();
    }

    @Override
    public void onRefresh() {
        mCurrentPage = 1;
        getData();
    }

    @Override
    protected boolean isPullToRefresh() {
        return true;
    }

    @Override
    protected boolean isLoadMore() {
        return true;
    }
    public class SubscriberAdapter extends BaseListAdapter {


        private ArrayList<SwipeLayout> openedItems = new ArrayList<SwipeLayout>();
        private OnCustomListener listener;
        private ViewHolder holder;


        public SubscriberAdapter(Context context) {
            super(context);
        }


        @Override
        public View getZkView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(parent.getContext(), R.layout.my_item_subscriber, null);
                holder = new ViewHolder();
                holder.tv_sub_icon = (ImageView) convertView.findViewById(R.id.tv_sub_icon);
                holder.rb_sub_stars = (RatingBar) convertView.findViewById(R.id.rb_sub_stars);
                holder.tv_sub_name = (TextView) convertView.findViewById(R.id.tv_sub_name);
                holder.tv_act_subbegin = (TextView) convertView.findViewById(R.id.tv_act_subbegin);
                holder.tv_act_subend = (TextView) convertView.findViewById(R.id.tv_act_subend);
                holder.tv_sub_delete = (TextView) convertView.findViewById(R.id.tv_sub_delete);
                holder.tv_sub_zhiding = (TextView) convertView.findViewById(R.id.tv_sub_zhiding);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            DriverSubscriptionData.DataBean bean = (DriverSubscriptionData.DataBean) adapter.getItem(position);

//            YncApplication.getInstance().loadCircleImage(getActivity(), bean.getUserImage(), R.drawable.shengfeng, R.drawable.shengfeng, holder.tv_sub_icon);
            BitmapUtil.showImgForNetPath(bean.getUserImage(),holder.tv_sub_icon);

            holder.rb_sub_stars.setRating(bean.getStar());
            if (!TextUtils.isEmpty(bean.getUsername())) {
                holder.tv_sub_name.setText(bean.getUsername());
            } else {
                holder.tv_sub_name.setText("");

            }
            if (bean.getShipperLine() != null) {
                if (bean.getShipperLine().getSPoint() != null) {
                    holder.tv_act_subbegin.setText(bean.getShipperLine().getSPoint());

                } else {
                    holder.tv_act_subbegin.setText("");

                }
                if (bean.getShipperLine() != null) {
                    holder.tv_act_subend.setText(bean.getShipperLine().getEPoint());

                } else {
                    holder.tv_act_subend.setText("");

                }
            } else {
                holder.tv_act_subbegin.setText("");
                holder.tv_act_subend.setText("");


            }
            holder.tv_sub_delete.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        listener.onCustomerListener(holder.tv_sub_delete, position);
                    }

                }
            });
            holder.tv_sub_zhiding.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        listener.onCustomerListener( holder.tv_sub_zhiding, position);
                    }

                }
            });
            SwipeLayout sl_sub = (SwipeLayout) convertView.findViewById(R.id.sl_sub);

            sl_sub.setOnSwipeListener(new MySwipeListener());

            return convertView;
        }

        class ViewHolder {
            ImageView tv_sub_icon;
            TextView tv_sub_name;
            TextView tv_act_subbegin;
            TextView tv_sub_delete;
            TextView tv_sub_zhiding;
            TextView tv_act_subend;
            RatingBar rb_sub_stars;
        }

        public void closeAllItems() {
            // 关闭当前所有打开的条目
            for (int i = 0; i < openedItems.size(); i++) {
                openedItems.get(i).close();
            }

            // 集合清除
            openedItems.clear();
        }

        class MySwipeListener implements SwipeLayout.OnSwipeListener {

            @Override
            public void onOpen(SwipeLayout layout) {
                // 记录当前被开打的条目
                openedItems.add(layout);
            }

            @Override
            public void onClose(SwipeLayout layout) {
                // 关闭了就从集合中移除
                openedItems.remove(layout);
            }

            @Override
            public void onStartOpen(SwipeLayout layout) {
                // 新的条目将要打开
                closeAllItems();
            }

            @Override
            public void onStartClose(SwipeLayout layout) {

            }
        }

        /**
         * 设置适配器上，某个控件的监听事件
         *
         * @param listener
         */
        public void setOnCustomListener(OnCustomListener listener) {
            this.listener = listener;
        }
    }

}
